#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 将文件描述符包装成文件对象
问题: 你有一个对应于操作系统上一个已打开的I/O通道(比如文件、管道、套接字等)的整型文件描述符， 你想将它包装成一个更高层的Python文件对象。
提示 :
"""

import os
from socket import socket, AF_INET, SOCK_STREAM
import sys

def recipe1():
    # 打开一个低级文件描述符
    fd = os.open('18_file_descriptor.txt', os.O_WRONLY | os.O_CREAT)

    # 转换为正确的文件
    f = open(fd, 'wt')
    f.write('Hello \n')
    f.close()

def recipe2():
    '''输出二进制数据到标准输出'''
    bstdout = open(sys.stdout.fileno(), 'wb', closefd=False)
    bstdout.write(b'Hello World!\n')
    bstdout.write('张三'.encode('utf-8'))
    bstdout.flush()

def echo_client(client_sock, addr):
    print('Got connection from', addr)

    # Make text-mode file wrappers for socket reading/writing
    client_in = open(client_sock.fileno(), 'rt', encoding='latin-1', closefd=False)
    client_out = open(client_sock.fileno(), 'wt', encoding='latin-1', closefd=False)

    # Echo lines back to the client using file I/O
    for line in client_in:
        client_out.write(line)
        client_out.flush()

    client_sock.close()

def echo_server(address):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind(address)
    sock.listen(1)
    while True:
        client, addr = sock.accept()
        echo_client(client, addr)

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()

if __name__ == '__main__':
    main()         